package config;

import javax.sql.DataSource;
import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;

@Configuration
@Order(2)
public class SqlSessionFactoryConf {

//    @Bean
    public static SqlSessionTemplate sqlSessionTemplate(SqlSessionFactoryBean sqlSessionFactoryBean) throws Exception {
        SqlSessionTemplate template=new SqlSessionTemplate(sqlSessionFactoryBean.getObject());
        return template;
    }

    @Bean
    public  static SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTransactionFactory(new ManagedTransactionFactory());
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("resources/mybatisConf.xml"));
        return sqlSessionFactoryBean;
    }

//    @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setAnnotationClass(Repository.class);
        scannerConfigurer.setBasePackage("org.mybatis.builder");
        return scannerConfigurer;
    }

//    @Bean
    public static DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager manager=new DataSourceTransactionManager(dataSource);
        return manager;
    }

}
